package com.kaka.bus.engine.invite;

import android.content.Intent;
import android.graphics.Color;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.kaka.bus.R;
import com.kaka.bus.adapter.InviteAdapter;
import com.kaka.bus.adapter.InviteRuleAdapter;
import com.kaka.bus.base.BaseActivity;
import com.kaka.bus.bean.CommissionBean;
import com.kaka.bus.bean.HttpWrapper;
import com.kaka.bus.bean.InviteBean;
import com.kaka.bus.bean.InviteRule;
import com.kaka.bus.bean.ShareBean;
import com.kaka.bus.constant.Constant;
import com.kaka.bus.constant.EventConstant;
import com.kaka.bus.engine.home.info.bank.add.AddBankActivity;
import com.kaka.bus.listener.Listener;
import com.kaka.bus.util.ShareUtil;
import com.kaka.bus.util.StatusBarUtil;
import com.kaka.bus.util.U;
import com.kaka.bus.view.dialog.TempletDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;

/**
 * Created by OnionMac on 2018/4/16.
 */

public class InviteActivity extends BaseActivity<InvitePresenter> implements InviteContract.View {

    @BindView(R.id.toolbar_back)
    ImageView mToolbarBack;
    @BindView(R.id.toolbar_name)
    TextView mToolbarName;
    @BindView(R.id.toolbar_rl)
    RelativeLayout mToolbarRl;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.invite_swipe)
    SwipeRefreshLayout mInviteSwipe;
    @BindView(R.id.invite_rule)
    ImageView mInviteRule;
    @BindView(R.id.invite_recy_friend)
    RecyclerView mInviteRecyFriend;
    @BindView(R.id.invite_smart_friend)
    SmartRefreshLayout mInviteSmartFriend;
    @BindView(R.id.invite_recy_friends)
    RecyclerView mInviteRecyFriends;
    @BindView(R.id.invite_smart_friends)
    SmartRefreshLayout mInviteSmartFriends;

    public static final int LEVEL_MY = 1;
    public static final int LEVEL_MY_SUB = 2;

    public static final int CAN_WITHDRAW = 1;
    @BindView(R.id.invite_mycode)
    TextView mInviteMycode;
    @BindView(R.id.invite_allcommission)
    TextView mInviteAllcommission;
    @BindView(R.id.invite_usecommission)
    TextView mInviteUsecommission;
    @BindView(R.id.invite_share1)
    TextView mInviteShare1;
    @BindView(R.id.invite_withdraw)
    TextView mInviteWithdraw;
    @BindView(R.id.invite_share2)
    TextView mInviteShare2;

    private List<InviteBean> mMyDatas = new ArrayList<>();
    private List<InviteBean> mMySubDatas = new ArrayList<>();

    private InviteAdapter mInviteAdapter;

    private InviteAdapter mInviteAdapters;
    private TempletDialog mInvitedialog;

    private int mPage = 1;
    private int mPageSize = 50;

    private int mCanWithdraw = 1;

    /**
     * 需要绑定银行卡才能提现
     */
    private String TO_BINDBANK = "202";

    private ShareBean mShareBean;

    /**
     * 自定义分享
     */
    private BottomSheetDialog mBottomSheetDialog;

    @Override
    protected void initView() {
        super.initView();

        MobclickAgent.onEvent(this, EventConstant.ENTER_INVITE_PAGE);

        mToolbarName.setText("邀请好友");
        mToolbar.setOnClickListener(v -> finish());
        StatusBarUtil.setTranslucentForImageViewInFragment(this, null);
        mToolbarRl.setBackgroundColor(Color.TRANSPARENT);
        ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) mToolbar.getLayoutParams();
        layoutParams.topMargin = U.getBarHeight(this.getApplication());
        mToolbar.setLayoutParams(layoutParams);

        mBottomSheetDialog = new BottomSheetDialog(this);
        setShareView();
        /**
         * swipe的下拉高度
         */
        mInviteSwipe.setProgressViewEndTarget(false, 300);
        mInviteSwipe.setColorSchemeColors(getResources().getColor(R.color.red_money));

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
//        linearLayoutManager.setSmoothScrollbarEnabled(true);
//        linearLayoutManager.setAutoMeasureEnabled(true);

        mInviteRecyFriend.setLayoutManager(linearLayoutManager);
        mInviteAdapter = new InviteAdapter(R.layout.item_invite, mMyDatas);
        mInviteRecyFriend.setAdapter(mInviteAdapter);

//        mInviteRecyFriend.setHasFixedSize(true);
//        mInviteRecyFriend.setNestedScrollingEnabled(false);

        mInviteRecyFriends.setLayoutManager(new LinearLayoutManager(this));
        mInviteAdapters = new InviteAdapter(R.layout.item_invite, mMySubDatas);
        mInviteRecyFriends.setAdapter(mInviteAdapters);
//        mInviteRecyFriends.setHasFixedSize(true);
//        mInviteRecyFriends.setNestedScrollingEnabled(false);

        mInvitedialog = new TempletDialog.Builder(this)
                .setLayout(R.layout.dialog_invite).setWidthPer(0.85).setMoveY(-10)
                .setWindowAnim(R.style.person＿dialog_anim).build();

        /**
         * 设置默认邀请码
         */
        mInviteMycode.setText(getUserId());
    }

    /**
     * 设置分享链接
     */
    private void setShareView() {
        mBottomSheetDialog.setContentView(R.layout.item_share);
    }

    @Override
    protected void initData() {
        /**
         * 这三个接口其实可以做成一个接口 !
         */
        mPresenter.getInviteRule();
        mPresenter.getInviteCommission(getUserId());   //OK
        mPresenter.getInviteShare(getUserId());

        /**
         * 列表
         */
        mPresenter.getInviteList(getUserId(),mPage,mPageSize,LEVEL_MY);   //OK
        mPresenter.getInviteList(getUserId(),mPage,mPageSize,LEVEL_MY_SUB);  //B、U OK
    }

    @Override
    protected void initListener() {
        super.initListener();
        mInviteRule.setOnClickListener(v -> mInvitedialog.show());

        mInviteSwipe.setOnRefreshListener(() -> {
            mInviteSwipe.setRefreshing(false);
        });

        mInviteSmartFriend.setOnLoadmoreListener(refreshlayout -> {
            mPresenter.getInviteListLoadMore(getUserId(),++mPage, mPageSize,LEVEL_MY);
        });

        mInviteSmartFriends.setOnLoadmoreListener(refreshlayout -> {
            mPresenter.getInviteListLoadMore(getUserId(),++mPage, mPageSize,LEVEL_MY_SUB);
        });

        mInviteWithdraw.setOnClickListener(v -> {
            /**
             * 可以提现  1
             */
            if(mCanWithdraw == CAN_WITHDRAW){
                U.getSlectDialog(this, "提示", "是否确认要提现?", "否", "确认", new Listener.OnNormalAlertDialogChooseClickListener() {
                    @Override
                    public void onLeft() {

                    }

                    @Override
                    public void onRight() {
                        mPresenter.commissionWithdraw(getUserId());
                    }
                }).show();
            }else{
                showMessage("对不起,您暂时不能提现");
            }
        });

        mInviteShare1.setOnClickListener(v -> {
            share();
        });

        mInviteShare2.setOnClickListener(v -> {
            share();
        });
    }


    @Override
    public void onInviteRuleResult(HttpWrapper<InviteRule> wrapper) {

        if(Constant.SUCCESS_CODE.equals(wrapper.code)){
            InviteRule data = wrapper.getData();
            mInvitedialog.show();

            RecyclerView recyclerView = mInvitedialog.findViewById(R.id.dialog_invite_recy);
            ImageView image = mInvitedialog.findViewById(R.id.dialog_invite_center);
            ImageView close = mInvitedialog.findViewById(R.id.dialog_invite_close);
            close.setOnClickListener(v -> mInvitedialog.dismiss());
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            InviteRuleAdapter inviteRuleAdapter = new InviteRuleAdapter(R.layout.item_invite_rule, data.getRules());
            recyclerView.setAdapter(inviteRuleAdapter);
            Glide.with(this).load(data.getImage()).into(image);
        }else{
            showMessage(wrapper.getInfo());
        }

    }

    @Override
    public void onInviteCommissionResult(HttpWrapper<CommissionBean> wrapper) {

        if(Constant.SUCCESS_CODE.equals(wrapper.code)){
            CommissionBean data = wrapper.getData();
            if(data == null){
                return;
            }
            mInviteMycode.setText(data.getInviteId());
            mCanWithdraw = data.getCanWithdraw();
            mInviteAllcommission.setText(data.getCommissionTotal());
            mInviteUsecommission.setText(data.getCommissionBalance());

            if(mCanWithdraw == CAN_WITHDRAW){
                mInviteWithdraw.setBackgroundResource(R.mipmap.yqhy_buttun_fx);
            }else{
                mInviteWithdraw.setBackgroundResource(R.mipmap.yqhy_buttun_fx_disabled);
            }
        }else {
            showMessage(wrapper.getInfo());
        }
    }

    @Override
    public void onCommissionWithdrawResult(HttpWrapper<String> wrapper) {
        if(Constant.SUCCESS_CODE.equals(wrapper.code)){
            showMessage(wrapper.info);
        }else if (TO_BINDBANK.equals(wrapper.code)){
            U.getSlectDialog(this, "提示", "请先绑定银行卡,小悠才能给你发钱哦", "取消", "去绑卡", new Listener.OnNormalAlertDialogChooseClickListener() {
                @Override
                public void onLeft() {

                }

                @Override
                public void onRight() {
                    startActivity(new Intent(InviteActivity.this, AddBankActivity.class));
                }
            }).show();
        }else{
            showMessage(wrapper.info);
        }

    }

    @Override
    public void onShareResult(HttpWrapper<ShareBean> wrapper) {
        if(Constant.SUCCESS_CODE.equals(wrapper.code)){
            mShareBean = wrapper.getData();
        }
    }

    @Override
    public void onInviteListResult(HttpWrapper<List<InviteBean>> data, int level) {
        if(Constant.SUCCESS_CODE.equals(data.code)){
            List<InviteBean> list = data.getData();
            if(level == LEVEL_MY){
                mMyDatas.clear();
                mMyDatas.addAll(list);
                mInviteAdapter.notifyDataSetChanged();
            }else if(level == LEVEL_MY_SUB){
                mMySubDatas.clear();
                mMySubDatas.addAll(list);
                mInviteAdapters.notifyDataSetChanged();
            }
        }else{
            showMessage(data.getInfo());
        }

    }

    @Override
    public void onListError() {

    }

    @Override
    public void onListLoadMoreError() {
        finishLoadMore();
    }

    public void finishLoadMore(){
        mInviteSmartFriend.finishLoadmore(0);
        mInviteSmartFriends.finishLoadmore(0);
    }

    @Override
    public void onInviteListLoadMoreResult(HttpWrapper<List<InviteBean>> data, int level) {
        finishLoadMore();
        if(Constant.SUCCESS_CODE.equals(data.code)){
            List<InviteBean> list = data.getData();
            if(list == null || list.size() <= 0){
                showMessage("没有更多数据了~");
                mPage -- ;
                return;
            }

            if(level == LEVEL_MY){
                mInviteAdapter.addData(list);
            }else if(level == LEVEL_MY_SUB){
                mInviteAdapters.addData(list);
            }
        }else{
            mPage -- ;
        }
    }

    public void share(){
        MobclickAgent.onEvent(this, EventConstant.INVITE_CLICK_INVITE_BUTTON);

        ShareUtil.showShare(this, mShareBean,new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                /**
                 * 不得到优惠券
                 */
                showMessage("分享成功");
                MobclickAgent.onEvent(InviteActivity.this, EventConstant.INVITE_SUCCESS);
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                showMessage("分享失败");
                MobclickAgent.onEvent(InviteActivity.this, EventConstant.INVITE_ERROR);
            }

            @Override
            public void onCancel(Platform platform, int i) {
                showMessage("分享取消");
                MobclickAgent.onEvent(InviteActivity.this, EventConstant.INVITE_CANCEL);

            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_invate;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }
}
